<template>
  <!-- 图片算法 -->
  <el-row>
    <el-col :span="5">
      <div class="box">
        <el-scrollbar>
          <basic-container>
            <avue-tree :option="treeOption" :data="treeData" @node-click="nodeClick"
              :filter-node-method="filterNodeMethod" />
          </basic-container>
        </el-scrollbar>
      </div>
    </el-col>
    <el-col :span="19">
      <basic-container>
        <avue-crud :defaults.sync="defaults" :option="option" :search.sync="search" :table-loading="loading" :data="data"
          ref="crud" v-model="form" :permission="permissionList" @row-del="rowDel" @row-update="rowUpdate"
          @row-save="rowSave" :before-open="beforeOpen" :page.sync="page" @search-change="searchChange"
          @search-reset="searchReset" @selection-change="selectionChange" @current-change="currentChange"
          @size-change="sizeChange" @refresh-change="refreshChange" @on-load="onLoad">
          <template slot="status" slot-scope="scope">
            <avue-switch :value="scope.row.status == 1 ? true : false"
              @click="handleSwitchStatus(scope.row)"></avue-switch>
          </template>
          <!-- <template slot-scope="scope" slot="menu">
            <el-button v-if="scope.row.status == 2" type="text" size="small" icon="el-icon-info"
              @click.stop="updateStatus(scope.row.id, 1)">启用
            </el-button>
            <el-button v-else type="text" size="small" icon="el-icon-info" @click.stop="updateStatus(scope.row.id, 2)">禁用
            </el-button>
          </template> -->
          <template slot-scope="{type,disabled,row}" slot="value1Form">
            <el-row v-if="['add', 'edit'].includes(type)">
              <el-col :span="20">
                <el-input v-model="testValue" placeholder="请输入参数"></el-input>
              </el-col>
              <el-col :span="2" :push="1">
                <el-button type="info" round @click="test()">测试</el-button>
              </el-col>
            </el-row>
          </template>
          <template slot-scope="{type,disabled}" slot="ResultForm">
            <el-row>
              <el-input :readonly="true" placeholder="测试结果"></el-input>
            </el-row>
          </template>
        </avue-crud>
      </basic-container>
    </el-col>
  </el-row>
</template>

<script>
import {
  // getList,
  // getUser,
  getUserPlatform,
  // remove,
  // update,
  updatePlatform,
  // add,
  grant,
  resetPassword, unlock
} from "@/api/system/user";
import { exportBlob } from "@/api/common";
import { getList, getTenantTree, getDetail, add, update, remove, updateStatus, javascriptTest, jarTest } from "@/api/base/pictureAlgorithm";
import { mapGetters } from "vuex";
import website from '@/config/website';
import { getToken } from '@/util/auth';
import { downloadXls } from "@/util/util";
import { dateNow } from "@/util/date";
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import func from "@/util/func";

export default {
  data() {
    return {
      testValue: '',
      defaults: {},
      form: {},
      search: {},
      roleBox: false,
      excelBox: false,
      platformBox: false,
      initFlag: true,
      selectionList: [],
      query: {},
      loading: true,
      platformLoading: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      platformPage: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      init: {
        roleTree: [],
        deptTree: [],
      },
      roleGrantList: [],
      roleTreeObj: [],
      treeDeptId: '',
      treeData: [],
      treeOption: {
        nodeKey: 'id',
        lazy: true,
        treeLoad: function (node, resolve) {
          const parentId = (node.level === 0) ? 0 : node.data.id;
          getTenantTree(parentId).then(res => {
            resolve(res.data.data.map(item => {
              return {
                ...item,
                leaf: !item.hasChildren
              }
            }))
          });
        },
        addBtn: false,
        menu: false,
        size: 'small',
        props: {
          labelText: '标题',
          label: 'tenantName',
          value: 'tenantId',
          children: 'children'
        }
      },
      option: {
        height: 'auto',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchSpan: 5,
        searchMenuSpan: 5,
        border: true,
        index: true,
        viewBtn: true,
        selection: false,
        refreshBtn: false,
        columnBtn: false,
        searchShowBtn: false,
        dialogClickModal: false,
        column: [
          {
            label: "算法名称",
            prop: "algorithmName",
            search: true,
            rules: [{
              required: true,
              message: "请输入算法名称",
              trigger: "blur"
            }]
          },

          {
            label: "算法类型",//化验单类型
            prop: "algorithmType",
            type: "select",
            editDisabled: true,
            dicUrl: '/api/blade-platform/pictureAlgorithm/algorithmType',
            rules: [{
              required: true,
              message: "请选择",
              trigger: "blur"
            }]

          },
          {
            label: '算法图片',
            prop: 'url',
            type: 'upload',
            drag: true,
            loadText: '图片上传中，请稍等',
            span: 24,
            tip: '只能上传jpg/png格式的图片',
            listType: 'picture-img',
            propsHttp: {
              res: 'data',
              url: 'link',
            },
            action: "/api/blade-resource/oss/endpoint/put-file?code=minio",
            rules: [{
              required: true,
              message: "请选择算法图片",
              trigger: "blur"
            }]
          },
          {
            label: "脚本类型",//协议类型
            prop: "scriptType",
            type: "select",
            dicData: [{
              label: 'jar包',
              value: 1
            }, {
              label: 'java脚本',
              value: 2
            }],
            rules: [{
              required: true,
              message: "请选择",
              trigger: "blur"
            }]

          },
          {
            label: "类名",
            prop: "className",
            display: false,
            hide: true,
            // slot: true,
            // display: false
          },
          {
            label: "方法名",
            prop: "methodName",
            display: false,
            hide: true,
          },

          // {
          //   label: "文件地址",
          //   prop: "filePath",
          //   display: false,
          //   hide: true,
          //   append: '选择jar文件'
          // },
          {
            label: '文件地址',
            prop: 'filePath',
            type: 'upload',
            display: false,
            hide: true,
            drag: true,
            limit: 1,
            dataType: 'string',
            // loadText: '图片上传中，请稍等',
            // span: 24,
            // tip: '只能上传jpg/png格式的图片',
            data: {
              tenantId: '904969',
              // algorithmType: 'NO_CHECK'
            },
            propsHttp: {
              res: 'data',
              name: 'url',
              url: 'url',
            },
            action: "/api/blade-platform/file/upload"
          },

          {
            label: '脚本内容',
            prop: 'content',
            type: 'textarea',
            minRows: 2,
            maxRows: 5,
            display: false,
            hide: true,

          },
          {
            label: "jar入参",
            prop: 'value1',
            hide: true,
            // viewDisplay: false,
            display: false,
            formslot: true,
            // append: '测试'
          },
          {
            label: "状态",
            prop: 'status',
            type: 'switch',
            // slot: false,
            addDisplay: false,
            // formatter(val, value) {
            //   return value == '2' ? '禁用' : '启用'
            // }
          },
          {
            label: '创建时间',
            prop: 'createTime',
            type: 'datetime',
            addDisplay: false,
            editDisplay: false,
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            width: '150',
          },
          {
            label: "测试结果",
            prop: 'resultValue',
            type: 'textarea',
            hide: true,
            formslot: true,
            span: 24
          },
        ],

      },
      data: [],

    };
  },
  watch: {
    'form.tenantId'() {
      if (this.form.tenantId !== '' && this.initFlag) {
        this.initData(this.form.tenantId);
      }
    },
    'excelForm.isCovered'() {
      if (this.excelForm.isCovered !== '') {
        const column = this.findObject(this.excelOption.column, "excelFile");
        column.action = `/api/blade-user/import-user?isCovered=${this.excelForm.isCovered}`;
      }
    },
    'form.scriptType': {
      handler(val) {
        if (val == 1) {
          this.defaults.className.display = true
          this.defaults.methodName.display = true
          this.defaults.filePath.display = true
          this.defaults.content.display = false
          this.defaults.value1.display = true
        } else if (val == 2) {
          this.defaults.className.display = false
          this.defaults.methodName.display = false
          this.defaults.filePath.display = false
          this.defaults.content.display = true
          this.defaults.value1.display = true
        } else {
          this.defaults.className.display = false
          this.defaults.methodName.display = false
          this.defaults.filePath.display = false
          this.defaults.content.display = false
          this.defaults.value1.display = false
        }
      },
      immediate: true
    }
  },
  computed: {
    ...mapGetters(["userInfo", "permission"]),
    permissionList() {
      return {
        // addBtn: this.vaildData(this.permission.user_add, false),
        // viewBtn: this.vaildData(this.permission.user_view, false),
        // delBtn: this.vaildData(this.permission.user_delete, false),
        // editBtn: this.vaildData(this.permission.user_edit, false)
      };
    },
    platformPermissionList() {
      return {
        // addBtn: false,
        // viewBtn: false,
        // delBtn: false,
        // editBtn: this.vaildData(this.permission.user_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  mounted() {
    // 非租户模式默认加载管理组数据
    if (!website.tenantMode) {
      this.initData(website.tenantId);
    }
  },
  methods: {
    handleSwitchStatus(row) {
      if (row.status == 1) {
        this.updateStatus(row.id, 2)
      } else {
        this.updateStatus(row.id, 1)
      }
    },
    test() {
      const { scriptType, className, methodName, filePath, content } = this.form
      if (scriptType === 1) {
        jarTest({
          body: this.testValue,
          className,
          methodName,
          filePath,
        }).then((res) => {
          const data = res.data.data
          this.form.resultValue = data
        }).catch((err) => {
          console.log('err', err);
        })
      } else {
        javascriptTest({
          body: this.testValue,
          protocolContent: content
        }).then((res) => {
          const data = res.data.data
          this.form.resultValue = data
        }).catch((err) => {
          console.log('err', err);
        })
      }



    },
    filterNodeMethod(value, data) {
      if (!value) return true;
      return data.tenantName.indexOf(value) !== -1;
    },
    updateStatus(id, status) {
      updateStatus(id, status).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
      });
    },
    nodeClick(data) {
      this.treeDeptId = data.tenantId;
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },
    initData(tenantId) {
      // getTenantTree(tenantId).then(res => {
      //   const column = this.findObject(this.option.group, "roleId");
      //   column.dicData = res.data.data;
      // });
      // getDeptTree(tenantId).then(res => {
      //   const column = this.findObject(this.option.group, "deptId");
      //   column.dicData = res.data.data;
      // });
      // getPostList(tenantId).then(res => {
      //   const column = this.findObject(this.option.group, "postId");
      //   column.dicData = res.data.data;
      // });
    },
    submitRole() {
      const roleList = this.$refs.treeRole.getCheckedKeys().join(",");
      grant(this.ids, roleList).then(() => {
        this.roleBox = false;
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        this.onLoad(this.page);
      });
    },

    rowSave(row, done, loading) {
      // if (this.treeDeptId == '') {
      //   this.$message({
      //     type: "warning",
      //     message: "医院不能为空"
      //   });
      //   return;
      // }
      const { algorithmName, algorithmType, scriptType, className, methodName, filePath, content, url } = row
      let item = {
        // tenantId: this.treeDeptId,
        algorithmName,
        algorithmType,
        url: url
      }
      if (scriptType === 1) {
        item = {
          ...item,
          className,
          methodName,
          filePath: filePath,
          scriptType
        }
      } else if (scriptType === 2) {
        item = {
          ...item,
          content,
          scriptType
        }
      }
      console.log('图片算法添加', JSON.stringify(item))
      add(item).then(() => {
        this.initFlag = false;
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done) {
      const { id, algorithmName, algorithmType, scriptType, className, methodName, filePath, content, url } = row
      let item = {
        id,
        // tenantId: this.treeDeptId,
        algorithmName,
        // algorithmType,
        url
      }
      if (scriptType === 1) {
        item = {
          ...item,
          className,
          methodName,
          filePath,
          scriptType
        }
      } else if (scriptType === 2) {
        item = {
          ...item,
          content,
          scriptType
        }
      }
      console.log('图片算法编辑', JSON.stringify(item))
      update(item).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      })


    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    searchReset() {
      this.query = {};
      this.treeDeptId = '';
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    handleReset() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择账号密码重置为123456?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return resetPassword(this.ids);
        })
        .then(() => {
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    handleGrant() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.roleTreeObj = [];
      if (this.selectionList.length === 1) {
        this.roleTreeObj = this.selectionList[0].roleId.split(",");
      }
      getRoleTree().then(res => {
        this.roleGrantList = res.data.data;
        this.roleBox = true;
      });
    },
    handlePlatform() {
      this.platformBox = true;
    },
    handleLock() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择账号解封？", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return unlock(this.ids);
        })
        .then(() => {
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleImport() {
      this.excelBox = true;
    },
    uploadAfter(res, done, loading, column) {
      window.console.log(column);
      this.excelBox = false;
      this.refreshChange();
      done();
    },
    handleExport() {
      const account = func.toStr(this.search.account);
      const realName = func.toStr(this.search.realName);
      this.$confirm("是否导出用户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        NProgress.start();
        exportBlob(`/api/blade-user/export-user?${this.website.tokenHeader}=${getToken()}&account=${account}&realName=${realName}`).then(res => {
          downloadXls(res.data, `用户数据表${dateNow()}.xlsx`);
          NProgress.done();
        })
      });
    },
    handleTemplate() {
      exportBlob(`/api/blade-user/export-template?${this.website.tokenHeader}=${getToken()}`).then(res => {
        downloadXls(res.data, "用户数据模板.xlsx");
      })
    },
    beforeOpen(done, type) {
      // if (["add"].includes(type)) {
      //   if (this.treeDeptId == '') {
      //     this.$message({
      //       type: "warning",
      //       message: "请选择需要添加图片算法的医院！！！"
      //     });
      //     return;
      //   }
      // }
      if (["edit"].includes(type)) {
        if (this.form.status == 1) {
          this.$message({
            type: "warning",
            message: "先停用，再编辑!"
          });
          return;
        }
      }
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
          // if (this.form.hasOwnProperty("deptId")) {
          //   this.form.deptId = this.form.deptId.split(",");
          // }
          // if (this.form.hasOwnProperty("roleId")) {
          //   this.form.roleId = this.form.roleId.split(",");
          // }
          // if (this.form.hasOwnProperty("postId")) {
          //   this.form.postId = this.form.postId.split(",");
          // }
        });
      }
      this.initFlag = true;
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query, {
        tenantId: this.treeDeptId
      })).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    platformRowUpdate(row, index, done, loading) {
      updatePlatform(row.id, row.userType, row.userExt).then(() => {
        this.platformOnLoad(this.platformPage);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    platformBeforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getUserPlatform(this.platformForm.id).then(res => {
          this.platformForm = res.data.data;
        });
      }
      done();
    },
    platformSearchReset() {
      this.platformQuery = {};
      this.platformOnLoad(this.platformPage);
    },
    platformSearchChange(params, done) {
      this.platformQuery = params;
      this.platformPage.currentPage = 1;
      this.platformOnLoad(this.platformPage, params);
      done();
    },
    platformSelectionChange(list) {
      this.platformSelectionList = list;
    },
    platformSelectionClear() {
      this.platformSelectionList = [];
      this.$refs.platformCrud.toggleSelection();
    },
    platformCurrentChange(currentPage) {
      this.platformPage.currentPage = currentPage;
    },
    platformSizeChange(pageSize) {
      this.platformPage.pageSize = pageSize;
    },
    platformRefreshChange() {
      this.platformOnLoad(this.platformPage, this.platformQuery);
    },
    platformOnLoad(page, params = {}) {
      this.platformLoading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query, {
        tenantId: this.treeDeptId
      })).then(res => {
        const data = res.data.data;
        this.platformPage.total = data.total;
        this.platformData = data.records;
        this.platformLoading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style>
.box {
  height: 800px;
}

.el-scrollbar {
  height: 100%;
}

.box .el-scrollbar__wrap {
  overflow: scroll;
}
</style>
